package middleware

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"taobao-merchandise/api/internal/types"
	"taobao-merchandise/pkg"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		get := r.Header.Get("token")
		if get == "" {
			httpx.OkJsonCtx(r.Context(), w, &types.Response{
				Code:    500,
				Message: "未登录",
				Data:    nil,
			})
			return
		}
		token, err := pkg.GetToken(get)
		if err != nil {
			httpx.OkJsonCtx(r.Context(), w, &types.Response{
				Code:    500,
				Message: err.Error(),
				Data:    nil,
			})
			return
		}
		r.ParseForm()
		r.Form.Set("fromUserId", token["user"].(string))
		// Passthrough to next handler if need
		//httpx.OkJsonCtx(r.Context(), w, &types.Response{
		//	Code:    200,
		//	Message: "token解析成功,user_id为Data",
		//	Data:    token["user"].(string),
		//})
		next(w, r)
	}
}
